﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace LookUpLater
{
    public class LookUpStatus
    {
        private static List<LookUpStatus> currentStatus;

        public Status status { get; set; }
        public string id { get; set; }
        public LookUpStatus(Status status, string id)
        {
            this.id = id;
            this.status = status;
        }
        public LookUpStatus(XElement element)
        {
            this.id = element.Attribute("id").Value;
            this.status = (Status)Enum.ToObject(typeof(Status),Convert.ToInt16(element.Attribute("status").Value));
        }
        public static List<LookUpStatus> CurrentStatus
        {
            get
            {
                if (currentStatus == null)
                    currentStatus = LoadXml();
                return currentStatus;
            }
        }

        private static List<LookUpStatus> LoadXml()
        {
            var xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "LookUpStatus.xml");
            var rootDoc = XDocument.Load(xmlPath).Element("LookUpStatus");
            var statusList = rootDoc.Elements("LookUp").Select(l => new LookUpStatus(l)).ToList();
            return statusList;
        }
        public static void Refresh()
        {
            currentStatus=LoadXml();
        }
        public bool SaveOrUpdate()
        {
            try
            {
                var xmlPath = Path.Combine(Directory.GetCurrentDirectory(), "LookUpStatus.xml");
                var rootDoc = XDocument.Load(xmlPath).Element("LookUpStatus");
                var curElenemt = rootDoc.Elements("LookUp").FirstOrDefault(l => new LookUpStatus(l).id.Equals(this.id));
                if (curElenemt != null)
                    curElenemt.SetAttributeValue("status", (int)this.status);
                else
                    rootDoc.Add(this.ToXML());
                rootDoc.Save(xmlPath);
            }
            catch
            {
                return false;
            }
            return true;
        }
        public static LookUpStatus GetStatusById(string id)
        {
            return CurrentStatus.FirstOrDefault(l => l.id == id);
        }
        
        public XElement ToXML()
        {
            return new XElement("LookUp", new XAttribute("id", this.id), new XAttribute("status", (int)status));
        }
    }
    public enum Status
    {
        LookedUp = 0,
        YetToLookUp = 1,
        Deleted = 2
    }
}
